package cn.exlu.coco.core.server.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import cn.exlu.coco.core.utils.DateUtil;
import cn.exlu.coco.core.utils.StringUtil;

public class FtpServer {
    private String ip;
    private String username;
    private String passwd;
    private int port = 21;
    private FTPClient ftpClient = null;
    
    public FtpServer(String ip, String username, String passwd){
        this.ip = ip;
        this.username = username;
        this.passwd = passwd;
    }
    
    public FtpServer(String ip, String username, String passwd, int port){
        this.ip = ip;
        this.username = username;
        this.passwd = passwd;
        this.port = port;
    }
    
    /**
     * 打开链接并登录
     * @return
     * @throws SocketException
     * @throws IOException
     */
    public boolean login() throws SocketException, IOException{
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        ftpClient.connect(ip, port); //连接ftp服务器
        ftpClient.login(username, passwd); //登录ftp服务器
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
//        if(!FTPReply.isPositiveCompletion(replyCode)){
//            return false;
//        }
        if (FTPReply.isPositiveCompletion(replyCode)) {
            ftpClient.enterLocalPassiveMode();//设置被动模式
        }
        return true;
    }
    
    /**
     * 删除服务器文件
     * @param remoteDirPath
     * @param remoteFileName
     * @return
     * @throws IOException 
     */
    public boolean delFile(String remoteDirPath, String remoteFileName) throws IOException{
        //切换FTP目录 
        ftpClient.changeWorkingDirectory(remoteDirPath); 
        int replyCode = ftpClient.dele(remoteFileName); 
        if(!FTPReply.isPositiveCompletion(replyCode)){
            return false;
        }
        
        return true;
    }
    
    /**
     * 上传文件
     * @param remoteDirPath
     * @param remoteFileName
     * @param localFilePath
     * @return
     * @throws IOException
     */
    public boolean upload(String remoteFileName, String localFilePath) throws IOException{
        InputStream inputStream = null;
        try{
            inputStream = new FileInputStream(new File(localFilePath));
            return ftpClient.storeFile(remoteFileName, inputStream);
        }catch (IOException e) {
            throw e;
        }finally{
            if(inputStream != null){
                inputStream.close();
            } 
        }

    }
    
    /**
     * 上传文件
     * @param remoteDirPath
     * @param remoteFileName
     * @param localFilePath
     * @return
     * @throws IOException
     */
    public boolean upload(String remoteDirPath, String remoteFileName, String localFilePath) throws IOException{
        
        mkdirCdDir(remoteDirPath);
//        ftpClient.makeDirectory(remoteDirPath);
//        ftpClient.changeWorkingDirectory(remoteDirPath);
        InputStream inputStream = null;
        try{
            inputStream = new FileInputStream(new File(localFilePath));
            ftpClient.storeFile(remoteFileName, inputStream);
        }catch (IOException e) {
            throw e;
        }finally{
            if(inputStream != null){
                inputStream.close();
            } 
        }

        return true;
        
    }
    
    /**
     * 获取远程目录下的文件列表
     * @param pathFolderRemote
     * @return
     */
    public FTPFile[] listFile() {
    	return listFile(null, null);
    }
    
    /**
     * 获取远程目录下的文件列表
     * @param pathFolderRemote
     * @param comparator
     * @return
     */
    public FTPFile[] listFile(String pathFolderRemote, Comparator<FTPFile> comparator ) {
		try {

			// 切换FTP目录
			if(!StringUtil.isNullOrEmpty(pathFolderRemote)) {
				ftpClient.changeWorkingDirectory(pathFolderRemote);
			}

			FTPFile[] ftpFiles = ftpClient.listFiles();
			
			if(comparator != null) {
				Arrays.sort(ftpFiles, comparator);
//				// 倒序排序
//				Arrays.sort(ftpFiles, new Comparator<FTPFile>() {
//
//					@Override
//					public int compare(FTPFile o1, FTPFile o2) {
//						// TODO Auto-generated method stub
//						return (int) -(o1.getTimestamp().getTimeInMillis() - o2.getTimestamp().getTimeInMillis());
//					}
//				});
			}
			
			return ftpFiles;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		
		return new FTPFile[0];
          
    }
    
    /**
     * 下载文件
     * @param ftpFile
     * @param fileLocal
     * @return
     * @throws Exception 
     */
    public boolean downloadFile(FTPFile ftpFile, File fileLocal) throws Exception {
    	boolean flag = false;
    	OutputStream os=null;

    	try {
    		os = new FileOutputStream(fileLocal);
    		ftpClient.retrieveFile(fileLocal.getName(), os); 
    		flag = true; 
      } catch (Exception e) { 
          throw e;
      } finally{  
          if(null != os){
              try {
                  os.close();
              } catch (IOException e) {
                  e.printStackTrace();
              } 
          } 
      } 
    	return flag;
    }
    
    /**
     * 下载文件
     * @param ftpFile
     * @param localPathFolder
     * @return
     * @throws Exception 
     */
    public boolean downloadFile(FTPFile ftpFile, String localPathFolder) throws Exception {
    	return downloadFile(ftpFile, localPathFolder, ftpFile.getName());
    }
    
    /**
     * 下载文件
     * @param ftpFile
     * @param localPathFolder
     * @param fileName
     * @return
     * @throws Exception 
     */
    public boolean downloadFile(FTPFile ftpFile, String localPathFolder, String fileName) throws Exception {
    	File localFile = new File(localPathFolder,fileName);
    	return downloadFile(ftpFile, localFile);
    }
    
//    /**
//     * 下载目录下的最新文件
//     * @param pathname
//     * @param localpath
//     * @return
//     */
//    public boolean downloadFileNewest(String pathFolder, String localpath) {
//    	boolean flag = false; 
//        OutputStream os=null;
//        try { 
////            System.out.println("开始下载文件");
//            //切换FTP目录 
//            ftpClient.changeWorkingDirectory(pathFolder); 
//            FTPFile[] ftpFiles = ftpClient.listFiles();
//            // 倒序排序
//            Arrays.sort(ftpFiles, new Comparator<FTPFile>() {
//
//				@Override
//				public int compare(FTPFile o1, FTPFile o2) {
//					// TODO Auto-generated method stub
//					return (int)-(o1.getTimestamp().getTimeInMillis() - o2.getTimestamp().getTimeInMillis());
//				}});
//            for(FTPFile file : ftpFiles){
//           	 System.out.println(file.getName() + ":" + file.getTimestamp().getTimeInMillis());
////                if(filename.equalsIgnoreCase(file.getName())){ 
////                    File localFile = new File(localpath + "/" + file.getName()); 
////                    os = new FileOutputStream(localFile); 
////                    ftpClient.retrieveFile(file.getName(), os); 
////                    os.close(); 
////                } 
//            } 
////            ftpClient.logout(); 
//            flag = true; 
////            System.out.println("下载文件成功");
//        } catch (Exception e) { 
////            System.out.println("下载文件失败");
//            e.printStackTrace(); 
//        } finally{ 
////            if(ftpClient.isConnected()){ 
////                try{
////                    ftpClient.disconnect();
////                }catch(IOException e){
////                    e.printStackTrace();
////                }
////            } 
//            if(null != os){
//                try {
//                    os.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } 
//            } 
//        } 
//        
//        return flag;
//    }
    
//    /** * 下载文件 * 未处理 TODO
//     * @param pathname FTP服务器文件目录 * 
//     * @param filename 文件名称 * 
//     * @param localpath 下载后的文件路径 * 
//     * @return */
//     public  boolean downloadFile(String pathname, String filename, String localpath){ 
//         boolean flag = false; 
//         OutputStream os=null;
//         try { 
//             System.out.println("开始下载文件");
//             //切换FTP目录 
//             ftpClient.changeWorkingDirectory(pathname); 
//             FTPFile[] ftpFiles = ftpClient.listFiles();
////             Arrays.sort(a, c);
//             for(FTPFile file : ftpFiles){
//            	 System.out.println(file.getName());
////                 if(filename.equalsIgnoreCase(file.getName())){ 
////                     File localFile = new File(localpath + "/" + file.getName()); 
////                     os = new FileOutputStream(localFile); 
////                     ftpClient.retrieveFile(file.getName(), os); 
////                     os.close(); 
////                 } 
//             } 
////             ftpClient.logout(); 
//             flag = true; 
//             System.out.println("下载文件成功");
//         } catch (Exception e) { 
//             System.out.println("下载文件失败");
//             e.printStackTrace(); 
//         } finally{ 
//             if(null != os){
//                 try {
//                     os.close();
//                 } catch (IOException e) {
//                     e.printStackTrace();
//                 } 
//             } 
//         } 
//         return flag; 
//     }

    /**
     * 切换到主目录
     * @return
     * @throws IOException
     */
    public boolean cdHome() throws IOException{
       return cdDir("~");
    }
    
    public boolean cdDir(String romete) throws IOException{
        return ftpClient.changeWorkingDirectory(romete);
    }

    /**
     * 退出并关闭链接
     * @return
     * @throws IOException
     */
    public boolean logout() throws IOException{
        ftpClient.logout();
        
        if(ftpClient.isConnected()){ 
            try{
                ftpClient.disconnect();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        
//        ftpClient.disconnect();
        return true;
    }

    // 创建多层目录文件，如果有ftp服务器已存在该文件，则不创建，如果无，则创建
    public boolean mkdirCdDir(String remote) throws IOException {
        boolean success = true;
        String directory = remote + "/";
        // 如果远程目录不存在，则递归创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("UTF8"), "GB2312");
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (mkdirDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
//                        System.out.println("创建目录[" + subDirectory + "]失败");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    //改变目录路径
    private boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
        } catch (IOException e) {
            return false;
        }
        return flag;
    }

    //判断ftp服务器文件是否存在    
    private boolean existFile(String path) throws IOException {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }

    //创建目录
    private boolean mkdirDirectory(String dir) {
        boolean flag = false;
        try {
            flag = ftpClient.makeDirectory(dir);
           return flag;
        } catch (Exception e) {
            
        }
        return flag;
    }

    public static void main(String[] args) throws SocketException, IOException {
///*//        FtpServer server = new FtpServer("125.210.127.99", "ftpuser", "ftpuser");
//        FtpServer server = new FtpServer("10.251.6.178", "upload", "upload", 21);
        FtpServer server = new FtpServer("125.210.127.229", "djxd", "djxd!@#", 21);
        server.login();
        server.cdDir("/20181214");
        long gmt = 8 * 60 * 60 * 1000; // FTP使用GMT时间导致8小时误差
        long gmt_first = gmt + 5 * 60 * 1000;
        final Date curDate = DateUtil.currentBusDate();
//        curDate.setTime(1544759040021L);
        System.out.println(curDate.getTime());
        
        FTPFile ftpFiles[] = server.listFile();
        for(FTPFile ftpFile :ftpFiles) {
        	if((ftpFile.getTimestamp().getTimeInMillis() + gmt_first) < curDate.getTime())  {
        		continue;
        	}else {
        		System.out.println(ftpFile.getName() + "______" + (ftpFile.getTimestamp().getTimeInMillis() + 8 * 60 * 60 * 1000));
        	}
        	
        }
//        server.downloadFile(ftpFile, "/home/mark/temp");
        server.logout();
        
//        boolean b;
//        b = server.upload("111.jpg", "/home/mark/temp/worksOrg/photo/descImg/37f2a5dd-ad89-40d8-8eb0-62a80fde083020180626160459679.jpg");
////        server.cdHome();
////        b = server.upload("photo", "test112.jpg", "/home/mark/temp/worksOrg/photo/descImg/37f2a5dd-ad89-40d8-8eb0-62a80fde083020180626160459679.jpg");
////        b = server.delFile("photo/desgImg", "test11.jpg");
//        server.logout();
//        System.out.println("Success:" + b);
//        
////        File file = new File("/home/mark/temp/worksOrg/photo/descImg/37f2a5dd-ad89-40d8-8eb0-62a80fde083020180626160459679.jpg");
////        System.out.println(file.getAbsolutePath());
////        System.out.println(file.getPath());
////        System.out.println(file.getCanonicalPath());
//        
//        
    }
}
